package com.flashcards.auth;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import com.flashcards.LogWrapper;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;

import oauth.signpost.http.HttpParameters;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;

public class OAuth {
    public static final String CONSUMER_KEY = "2389617439";
    public static final String CONSUMER_SECRETE = "d92fef9074e9a509187c9c6271e0e1e8";
    private CommonsHttpOAuthConsumer httpOauthConsumer;
    private OAuthProvider httpOauthprovider;
    public String consumerKey;
    public String consumerSecret;

    public OAuth()
    {
        this(CONSUMER_KEY, CONSUMER_SECRETE);
    }
    public OAuth(String consumerKey,String consumerSecret)
    {
        this.consumerKey=consumerKey;
        this.consumerSecret=consumerSecret;
    }

    public Boolean RequestAccessToken(Activity activity,String callBackUrl){
        Boolean ret=false;
        try{
            httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey,consumerSecret);
            httpOauthprovider = new DefaultOAuthProvider(
                    "http://api.t.sina.com.cn/oauth/request_token",
                    "http://api.t.sina.com.cn/oauth/access_token",
                    "http://api.t.sina.com.cn/oauth/authorize");
            httpOauthprovider.setOAuth10a(true);
            String authUrl = httpOauthprovider.retrieveRequestToken(httpOauthConsumer, callBackUrl);
            activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
            ret=true;
        }catch(Exception e){
            LogWrapper.i("##", "Failed", e);
        }
        return ret;
    }

    public UserInfo GetAccessToken(Intent intent){
        UserInfo user=null;
        Uri uri = intent.getData();
        String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
        try {
            httpOauthprovider.setOAuth10a(true);
            httpOauthprovider.retrieveAccessToken(httpOauthConsumer,verifier);
        } catch (OAuthMessageSignerException ex) {
            ex.printStackTrace();
        } catch (OAuthNotAuthorizedException ex) {
            ex.printStackTrace();
        } catch (OAuthExpectationFailedException ex) {
            ex.printStackTrace();
        } catch (OAuthCommunicationException ex) {
            ex.printStackTrace();
        }
        HttpParameters user_id= httpOauthprovider.getResponseParameters();
        LogWrapper.i("####", "=========Start========");
        for (Map.Entry<String, SortedSet<String>> stringSortedSetEntry : user_id.entrySet()) {
            LogWrapper.i("####", stringSortedSetEntry.getKey());
        }
        LogWrapper.i("####", "=========END========");
        String userKey = httpOauthConsumer.getToken();
        String userSecret = httpOauthConsumer.getTokenSecret();
        LogWrapper.i("####", userKey);
        LogWrapper.i("####", userSecret);
        user=new UserInfo("", userKey, userSecret);
        return user;
    }

    public HttpResponse SignRequest(String token,String tokenSecret,String url,List params)
    {
        HttpPost post = new HttpPost(url);

        try{
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
        }

        post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        return SignRequest(token,tokenSecret,post);
    }

    public HttpResponse SignRequest(String token,String tokenSecret,HttpPost post){
        httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey,consumerSecret);
        httpOauthConsumer.setTokenWithSecret(token,tokenSecret);
        HttpResponse response = null;
        try {
            httpOauthConsumer.sign(post);
        } catch (OAuthMessageSignerException e) {
            e.printStackTrace();
        } catch (OAuthExpectationFailedException e) {
            e.printStackTrace();
        } catch (OAuthCommunicationException e) {
            e.printStackTrace();
        }
        try {
            response = new DefaultHttpClient().execute(post);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
}
